package com.free.bsf.metric.controller;

import com.free.bsf.core.db.DbHelper;
import com.free.bsf.core.util.StringUtils;
import com.free.bsf.metric.Kafka;
import com.free.bsf.metric.base.Config;
import com.free.bsf.metric.dao.model.auto.tb_project_model;
import com.free.bsf.metric.dao.tb_project_dal;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("/api")
public class ApiController {

    @RequestMapping("/metric_page/")
    public String metric_page(@RequestBody String body) {
        System.out.println(body);
        Kafka.sendMessage("metric_page",body);
        return "{}";
    }

    @RequestMapping("/metric_event/")
    public String metric_event(@RequestBody String body) {
        System.out.println(body);
        Kafka.sendMessage("metric_event",body);
        return "{}";
    }
    @RequestMapping("/metric_log/")
    public String metric_log(@RequestBody String body) {
        System.out.println(body);
        Kafka.sendMessage("metric_log",body);
        return "{}";
    }

    @RequestMapping("/metric_config/")
    public String metric_config(String project) {
        if (project != null) {
            val appModel_cache = Config.LocalCache.get(Config.LocalCacheTime, "project:"+ StringUtils.nullToEmpty(project), () -> {
                return Optional.ofNullable(DbHelper.get(Config.mysqlDataSource(), (c) -> {
                    return new tb_project_dal().get(c, project);
                }));
            });
            if (appModel_cache.isPresent()) {
                val appModel = (tb_project_model) appModel_cache.get();
                return appModel.getFront_metric_config();
            }
        }
        return "[]";
    }

}